<template>
  <div class="stats-panel">
    <div class="stats-panel-head stats-form">
      <h3>{{ $t('report.staffCategoryChart.text1') }}</h3>
      <div class="stats-form-group stats-checkbox">
        <base-checkbox :value="categoryIgnoreNull" @input="chooseCategoryIgnore">{{ $t('report.staffCategoryChart.text2') }}</base-checkbox>
      </div>
     
      <div class="stats-form-group">
        <!-- <div id="staff-date-range" class="stats-form-daterange">
          <span>{{categoryStartTime}} - {{categoryEndTime}}</span> 
          <b class="caret"></b>
        </div> -->
        <date-picker @datePicker="datePicker" />
      </div>
    </div>
    <div class="stats-panel-body">
      <div style="text-align: center;">
        <div class="stats-btn-group">
          <button
            v-for="btn in btnOptions"
            :key="btn.value"
            type="button"
            :class="{'stats-checked': categoryType == btn.value}"
            @click="chooseCategoryType(btn.value)">
            {{ btn.name }}
          </button>
        </div>
      </div>
      <div class="category-chart-wrap">
        <div id="category"></div>
        <stats-chart-empty v-if="categoryEmpty">{{$t('common.base.tip.noData')}}</stats-chart-empty>
      </div>
      <div class="stats-staff-category-wrap" v-if="showTable">
        <div class="stats-table-header">
          <h3>{{ $t('report.performanceChart.callList') }}</h3>

          <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed">{{ $t('common.base.export') }}</button>          
          <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed">{{ $t('common.base.exportAll') }}</button>
          <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
        </div>
        <div>
          <el-table :data="page.list" class="stats-table">

            <el-table-column :label="$t('common.label.recordId')" prop="recordId" width="180px" show-overflow-tooltip>
              <template slot-scope="scope">
                <sample-tooltip :row="scope.row">
                  <template slot="content" slot-scope="{isContentTooltip}">
                    <el-tooltip :content="scope.row.recordId + ''" placement="top" :disabled="!isContentTooltip">
                      <a href="#" @click="openDetail(scope.row, `/setting/callcenter/view?id=${scope.row.id}&phone=${scope.row.userPhone}`)">{{scope.row.recordId}}</a>
                    </el-tooltip>
                  </template>
                </sample-tooltip>
              </template>
            </el-table-column>
            <el-table-column :label="$t('customer.detail.customerCallTable.table.label.agentName')"  prop="agentInfo.agentName"></el-table-column>
            <el-table-column :label="$t('common.label.callType')" prop="callTypeDisplayName"></el-table-column>
            <el-table-column :label="$t('customer.detail.customerCallTable.table.label.ringTime')" prop="ring" min-width="180px"></el-table-column>
            <el-table-column :label="$t('customer.detail.customerCallTable.table.label.consultCategory')" prop="zxCategoryName" show-overflow-tooltip></el-table-column>
            <el-table-column :label="$t('common.form.type.solveStatus')" prop="remarkStatus">
              <template slot-scope="scope">
                {{ scope.row.remarkStatus == 1 ? $t('common.base.resolved') : (scope.row.remarkStatus == 0 ? $t('common.base.notResolved') : '--') }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('report.callConsultChart.userPhone')" prop="userPhone" show-overflow-tooltip></el-table-column>
            <el-table-column :label="$t('common.base.customer')" prop="customerName" show-overflow-tooltip>
            </el-table-column>
            <el-table-column :label="$t('common.base.contact')" prop="linkmanName" show-overflow-tooltip></el-table-column>
            <el-table-column :label="$t('report.callConsultChart.totalDealings')" prop="totalDealings">
              <template slot-scope="scope">
                {{ scope.row.totalDealings | fmt_h_m_s}}
              </template>
            </el-table-column>

          </el-table>

          <el-pagination class="stats-pagination"
                         background @current-change="jump"
                         :current-page="page.pageNum"
                         layout="total, prev, pager, next"
                         :total="page.total">
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/* global AMap, moment, _init_data*/
import { t } from '@src/locales';
import _ from 'lodash';
import http from 'src/util/HttpUtil';
import qs from 'src/util/querystring';
import echarts from 'packages/Echarts';

import Loading from 'packages/BaseLoading';
import BaseCheckbox from 'packages/BaseCheckbox.vue';
import SampleTooltip from 'packages/SampleTooltip'
import { checkButtonDisplayed } from '@src/util/dom';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
let USER_CALL_LEGEND = [t('report.callcenter.text2'), t('report.callcenter.text13')];
const USER_CALL_COLOR = ['#48e8ab', '#6da9e7'];

const USER_SOLVED_LEGEND = [t('report.callcenter.text7'), t('report.callcenter.text6')];
const USER_SOLVED_COLOR = ['#48e8ab', '#6da9e7'];

const USER_TIME_LEGEND = [t('report.callcenter.text9')];
const USER_TIME_COLOR = ['#48e8ab'];

const USER_CALL_TPYE_LEGEND = [t('common.base.serviceEvent'), t('common.base.eventOrder'), t('common.base.systemKeyword.task'), t('task.setting.taskTypeSetting.flow.flowMap.review.name'), t('common.base.customer'),t('report.callcenter.text2') ];
const USER_CALL_TPYE_COLOR = ['#48e8ab', '#6da9e7', '#ffdd92', '#f56c6c', '#611335', '#062552'];

let category = null;

export default {
  name: 'staff-category-chart',
  props: ['callType', 'chartType', 'exportTrack'],
  data(){
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      sort: '',
      // value对应categoryType，是中文，国际化需要留意下~
      btnOptions: [{
        value: t('common.tabs.callList'),
        name: t('common.tabs.callList'),
        trackLabel: 'CALL', // 导出埋点用
      }, {
        value: t('report.staffCategoryChart.text3'),
        name: t('report.staffCategoryChart.text3'),
        trackLabel: 'SOLVE',
      }, {
        value: t('report.staffCategoryChart.text4'),
        name: t('report.staffCategoryChart.text4'),
        trackLabel: 'CALL_TIME',
      }],
      categoryType: t('common.tabs.callList'),
      categoryData: {},
      categoryIgnoreNull: true,
      categoryStartTime: '',
      categoryEndTime: '',
      categoryTeamId: '',
      categoryEmpty: false,

      showTable: false,
      model: {
        pageNum: 1,
        pageSize: 10,
        pageScence: ''
      },
      page: {},
      isFrist: true
    }
  },
  methods: {
    exportAllData(){
      let startDateTime = this.categoryStartTime,
        endDateTime = this.categoryEndTime;

      let model = {
        startDateTime, 
        endDateTime,
        pageScence: this.model.pageScence,
        exportAll: true
      };
    
      window.location.href = `/api/callcenter/outside/callcenter/excel/export/callrecord/common?${ qs.stringify(model)}`;

      this.exportTrackFn(true)
    },
    exportData(){
      let startDateTime = this.categoryStartTime,
        endDateTime = this.categoryEndTime;

      let model = {
        startDateTime, 
        endDateTime,
        pageScence: this.model.pageScence,
        agent:this.model.agent
      };
      window.location.href = `/api/callcenter/outside/callcenter/excel/export/callrecord/common?${ qs.stringify(model)}`;

      this.exportTrackFn(false)
    },
    exportTrackFn(isExportAll) {
      const tab = this.btnOptions.find(v => v.value === this.categoryType).trackLabel;
      this.exportTrack(isExportAll, tab)
    },
    openDetail(row, url){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `callCenterView_${ row.id}`, 
      //   title: '通话详情', 
      //   close: true, 
      //   url,
      //   fromId
      // }); 
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCallcenterView,
        key: row.id,
        params: `id=${row.id}&phone=${row.userPhone}`,
        fromId
      })
    },
    fetchTableData(){
      let startDateTime = this.categoryStartTime,
        endDateTime = this.categoryEndTime
      let model = {
        startDateTime, 
        endDateTime,
        pageScence: this.model.pageScence,
        page: this.model.pageNum,
        pageSize:this.model.pageSize,
        agent:this.model.agent
      };
      // console.info('model:', model);
      
      return http.get('/api/callcenter/outside/callcenter/callrecord/statistics/page/common', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);

      try {
        const res = await this.fetchTableData();
        this.page = res.result;
        this.showTable = true;
      } catch (error) {
        console.log(error);
      }

      instance.hide();
    },
    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    // 时间赋值
    initDate(start, end){
      this.categoryStartTime = start;
      this.categoryEndTime = end;
      if(this.isFrist) {
        setTimeout(() => {
          this.isFrist = false
          this.renderCategory();
        }, 1000)
      }else {
        this.renderCategory();
      }
    },
    // 初始化图表
    initCategory(){
      category = echarts.init(document.getElementById('category'));
      category.on('click', event => {
        this.model.pageNum = 1;
        let seriesName = event.seriesName;
        let origin = event.data._origin;
        // console.info('click::', seriesName, origin, origin.agent);
        this.model.agent = origin.agent;
        switch (seriesName) {
        case t('report.callcenter.text2'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = '呼入未接来电列表' 
          break;
        case t('report.callcenter.text5'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = '呼出未接来电列表' 
          break;
        case t('report.callcenter.text13'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = ' 呼入已接来电列表' 
          break;
        case t('report.callcenter.text4'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = '呼出已接来电列表' 
          break;
        case t('report.callcenter.text7'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = this.callType == 'call-in' ? '呼入未解决通话列表' : '呼出未解决通话列表'
          break;
        case t('report.callcenter.text6'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = this.callType == 'call-in' ? '呼入已解决通话列表' : '呼出已解决通话列表'
          break;
        case t('report.callcenter.text9'):
          // TODO国际化待办，接口入参，是否需要翻译
          this.model.pageScence = this.callType == 'call-in' ? '呼入通话时长列表' : '呼出通话时长列表'             
          break;
        default:
          break;
        } 
        
        this.renderTable()
      })

      category.on('legendselectchanged', event => {
        let arr = [];
        let opt = category.getOption();
        for(let [key, value] of Object.entries(event.selected)) {
          arr.push({key, value});
        }
        arr.some(item => {
          if(item.value) {
            this.sort = item.key;
            return true;
          }
        })

        if(this.categoryType == t('common.tabs.callList')) {
          let sort = this.sortCallTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.text3')) {
          let sort = this.sortSolvedTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.text4')) {
          let sort = this.sortTimeTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        } else if (this.categoryType == t('report.staffCategoryChart.text5')) {
          let sort = this.sortTimeTable();
          opt.series = sort.series;
          opt.yAxis[0].data = sort.yAxisData;
        }

        category.setOption(opt);
      })
      
    },
    chooseCategoryIgnore(value){
      this.categoryIgnoreNull = value;
      this.renderCategory();
    },
    chooseCategoryDate(start, end){
      this.$emit('trackEvent', 'chooseDate');

      this.categoryStartTime = start;
      this.categoryEndTime = end;
      this.renderCategory();
    },
    
    async renderCategory(event){
      console.log('event:', event);
      let instance = Loading.show(this.$el);
      try {
        const res = await this.fetchCategoryData();
        this.categoryData = res.result;
        instance.hide();
        this.showTable = false;
        this.setCategoryOption(event);
      } catch (error) {
        instance.hide();
        console.log(error)
      }
    },
    chooseCategoryType(type){
      // this.$emit('trackEvent', type);
      this.categoryType = type;
      this.setCategoryOption();
    },
    setCategoryOption(event){
      this.categoryEmpty = false;
      category && category.clear();

      let option = null;
      if(this.categoryType == t('common.tabs.callList')){
        let callOption = this.getCategoryCallOption();
        if(callOption) option = this.getCategoryOption(callOption);
      }

      if(this.categoryType == t('report.staffCategoryChart.text3')){
        let solveOption = this.getCategorySolvedOption();
        if(solveOption) option = this.getCategoryOption(solveOption);
      }

      if(this.categoryType == t('report.staffCategoryChart.text4')){
        let timeOption = this.getCategoryTimeOption()
        if(timeOption) option = this.getCategoryOption(timeOption);
      }
      
      if(null == option){
        this.categoryEmpty = true;
        return
      }

      category && category.setOption(option);
    },
    fetchCategoryData(){
      let startDateTime = this.categoryStartTime,
        endDateTime = this.categoryEndTime
      let params = {
        startDateTime, 
        endDateTime, 
        hideEmptyRecord: this.categoryIgnoreNull
      };
      params = {
        ...params,
        startDateTime: new Date(params.startDateTime).getTime(),
        endDateTime: new Date(params.endDateTime).getTime(),
      }
      const type = window.location.href.split('type=')[1];
      const url = `/api/callcenter/outside/callcenter/callcenteragent/statistics/${type === 'incoming-call' ? 'normal4Banner' : 'dialout4Banner'}`  
      return http.get(url, params)
    },
    getCategoryTimeOption(){
      let ctx = this;
      let data = this.categoryData.aboutDealings || [];
     
      if(data.length == 0){
        this.categoryEmpty = true;
        return 
      }
      this.categoryEmpty = false;      

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = [];

      data.sort((prev, next) => prev.lcount - next.lcount);
      data.forEach(item => {
        yAxisData.push(item.name);
        aauTime.push({
          value: item.lcount, 
          _origin: item
        });
      });

      series.push({
        name: USER_TIME_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      let option = {
        title: t('report.callcenter.text9'),
        legend: USER_TIME_LEGEND,
        color: USER_TIME_COLOR,
        tooltip: {
          formatter(data){            
            let html = '';
            let name = data[0].name;
            html += `<div>${name}</div>`;
            data.forEach(item => {          
              html += `<div>${item.marker} ${item.seriesName}: ${ctx.formatterTime(item.value >> 0)}</div>`;
            })
            return html;
          }
        },
        xAxis: {
          axisLabel: {
            show: true,
            formatter (value, index) {
              let temp = ctx.formatterTime(value >> 0);                            
              return temp == '--' ? 0 : temp;
            }
          }
        },
        yAxisData,
        series
      }

      return option;
    },
    sortTimeTable () {
      let time = this.categoryData.time || {};
      let data = [];
      for(let name in time){
        data.push(time[name]);
      }

      if(data.length == 0) return null;
      let yAxisData = [];
      let series = [];
      let aauTime = [];

      data.forEach(item => {
        yAxisData.push(item.name);

        aauTime.push({
          value: item.lcount, 
          _origin: item
        });

      });

      series.push({
        name: USER_TIME_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: aauTime,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategoryCallOption(){       
      let data = this.categoryData?.aboutRings || [];
     
      if(data.length == 0){
        this.categoryEmpty = true;
        return 
      }
      this.categoryEmpty = false;
     
      let yAxisData = [];
      let createdData = [];
      let finishedData = [];
      let series = [];
      
      data.forEach(item => {
        yAxisData.push(item.name);
        createdData.push({
          value: item.count,
          _origin: item
        });
        finishedData.push({
          value: item.secondCount,
          _origin: item
        });
      });
      
      series.push({
        name: USER_CALL_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_CALL_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.staffCategoryChart.text6'),
        legend: USER_CALL_LEGEND,
        color: USER_CALL_COLOR,
        yAxisData,
        series
      }
    },
    sortCallTable () {
      let aboutRings = this.categoryData?.aboutRings || {};
      let data = [];
      for(let name in aboutRings){
        data.push(aboutRings[name]);
      }

      if(data.length == 0) return null;

      let yAxisData = [];
      let createdData = [];
      let finishedDate = [];
      let series = [];
      
      if(this.sort == t('report.callcenter.text13')) {
        data.sort((prev, next) => prev.count - next.count);
      } else {
        data.sort((prev, next) => prev.secondCount - next.secondCount);
      }
      data.forEach(item => {
        yAxisData.push(item.name);
        createdData.push({
          value: item.count,
          _origin: item
        });
        finishedDate.push({
          value: item.secondCount,
          _origin: item
        });
      });

      series.push({
        name: USER_CALL_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: createdData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_CALL_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: finishedDate,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        series,
        yAxisData
      }
    },
    getCategorySolvedOption(){
      let series = [];
      let data = this.categoryData.aboutSolveds || [];
      
      if(data.length == 0) return null;

      let yAxisData = [];
      let satisData = [];// 未解决通话
      let generaldData = [];// 已解决通话

      data.forEach(item => {
        yAxisData.push(item.name);
        satisData.push({
          value: item.count,
          _origin: item
        });
        generaldData.push({
          value: item.secondCount,
          _origin: item
        });
      });

      series.push({
        name: USER_SOLVED_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_SOLVED_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        title: t('report.staffCategoryChart.text7'),
        legend: USER_SOLVED_LEGEND,
        color: USER_SOLVED_COLOR,
        yAxisData,
        series
      };
    },
    sortSolvedTable () {
      let series = [];
      let aboutSolveds = this.categoryData.aboutSolveds || {};
      let data = [];
      for(let name in aboutSolveds){
        data.push(aboutSolveds[name]);
      }

      if(data.length == 0) return null;

      let yAxisData = [];
      let satisData = [];
      let generaldData = [];
      if(this.sort == t('report.callcenter.text6')) {
        data.sort((prev, next) => prev.count - next.count);
      } else {
        data.sort((prev, next) => prev.secondCount - next.secondCount);
      }

      data.forEach(item => {
        yAxisData.push(item.name);
        satisData.push({
          value: item.count,
          _origin: item
        });
        generaldData.push({
          value: item.secondCount,
          _origin: item
        });
      });

      series.push({
        name: USER_SOLVED_LEGEND[0],
        type: 'bar',
        barMaxWidth: '30px',
        data: satisData,
        itemStyle : { normal: {label : {show: true}}}
      })

      series.push({
        name: USER_SOLVED_LEGEND[1],
        type: 'bar',
        barMaxWidth: '30px',
        data: generaldData,
        itemStyle : { normal: {label : {show: true}}}
      })

      return {
        yAxisData,
        series
      };
    },
    getCategoryOption(option){
      let yAxisData = option.yAxisData;

      let start = 0;
      let end = yAxisData.length - 1;
      if(yAxisData.length > 10) start = end - 9;

      let _option = {
        color: option.color,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: option.legend,
          top: '10px',
          left: '70px'
        },
        grid: {
          left: '20px',
          right: '60px',
          bottom: '20px',
          top: '50px',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {
              name: option.title
            }
          },
          right: 40
        },
        dataZoom: [
          {
            type: 'slider',
            show: true,
            yAxisIndex: [0],
            right: '20px',
            startValue: start,
            endValue: end,
            minValueSpan: 10,
            maxValueSpan: 30
          }
        ],
        yAxis: {
          type: 'category',
          data: option.yAxisData
        },
        xAxis: {
          type: 'value'
        },
        series: option.series
      };

      if(this.categoryType == t('report.staffCategoryChart.text4') && option.tooltip) {
        _.assign(_option.tooltip, option.tooltip);
      }

      if(option.xAxis) _.assign(_option.xAxis, option.xAxis)

      return _option;
    },
    formatterTime(sec){      
      // const DAY_SEC = 60 * 60 * 24;
      const HOUR_SEC = 60 * 60;
      const MIN_SEC = 60;

      // let day = sec / DAY_SEC >> 0;
      // sec = sec % DAY_SEC;

      let hour = sec / HOUR_SEC >> 0;
      sec = sec % HOUR_SEC;

      let min = sec / MIN_SEC >> 0;
      sec = sec % MIN_SEC;

      let temp = '';
      // if(day > 0) temp += day + '天';
      if(hour > 0) temp += `${hour }${t('common.base.hour')}`;
      if(min > 0) temp += `${min }${t('common.base.minute')}`;
      if(sec > 0) temp += `${sec }${t('common.base.second')}`;

      return temp ? temp : '--';
    },
    datePicker(data) {
      this.initDate(data[0], data[1])
      this.chartType && this.$track.commonFn.chartTrack(this.chartType, 'REPORT_SEARCH_TIME', this.$track)
    }
  },
  mounted(){
    this.initCategory();
    window.addEventListener('resize', _.debounce(function(){
      category.resize();
    }, 400))
  },
  watch: {
    categoryType(){
      this.showTable = false;
    },
    callType: {
      handler(newValue, oldValue) {
        // console.info('type:', newValue, oldValue);
        USER_CALL_LEGEND = newValue === 'call-in' ? [t('report.callcenter.text2'), t('report.callcenter.text13')] : [t('report.callcenter.text5'), t('report.callcenter.text4')]
        // this.initDate(moment().subtract(6, 'days'), moment());
      }
    }
  },
  components: {
    [BaseCheckbox.name]: BaseCheckbox,
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>

<style lang="scss">
#category{
  height: 100%;
}
.category-chart-wrap{
  width: 100%;
  height: 520px;
  position: relative;
}

.category-chart-empty{
  position: absolute;
  width: 100px;
  text-align: center;
  top: 120px;
  left: 50%;
  margin-left: -50px;
  font-size: 18px;
  font-weight: 500;
  color: #9a9a9a;
}

.el-tooltip__popper{
  max-width: 800px;
  word-break: break-all;
}
</style>

